# coding:utf-8
from typing import Dict, List

from fastapi import Query

from app.models.system import SystemRole, SystemRoleMenu, SystemMenu
from app.admin.schemas.system import RoleBase, RoleUpdate
from app.utils.array import ArrayUtil


class SystemRoleService:
    # 列表
    async def page_list(self, query: Query, page: int = 1, limit: int = 10):
        start = (page - 1) * limit
        count = await SystemRole.filter(is_deleted=False).filter(query).count()
        lists = await SystemRole.filter(is_deleted=False).filter(query).offset(start).limit(limit).all()
        return count, lists

    async def get_id(self, user_id: int):
        result = await SystemRole.get_or_none(id=user_id)
        return result

    async def find(self, query: Query):
        result = await SystemRole.get_or_none(query)
        return result

    async def create(self, obj_in: RoleBase):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        if obj_dict['remark'] is None:
            obj_dict['remark'] = ""
        result = await SystemRole.create(**obj_dict)
        return result

    async def update(self, obj_in: RoleUpdate):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        if obj_dict['remark'] is None:
            obj_dict['remark'] = ""
        # 删除键
        item_id = obj_dict.pop('id')
        result = await SystemRole.filter(id=item_id).update(**obj_dict)
        return result

    async def remove(self, item_id: int):
        item = await SystemRole.filter(id=item_id).first()
        if item:
            item.is_deleted = True
            await item.save()
            return True
        else:
            return False

    # 获取 role 所有菜单
    async def get_role_menu(self, role_id: int):
        menus = await SystemRoleMenu.filter(role_id=role_id).values_list('menu_id', flat=True)
        return menus

    # 更新 role 菜单
    async def update_role_menu(self, role_id: int, menu_ids: [int]):
        await SystemRoleMenu.filter(role_id=role_id).delete()
        # 使用循环组装列表
        result = [{"role_id": role_id, "menu_id": menu_id} for menu_id in menu_ids]
        print(result)
        menu_list = [SystemRoleMenu(**data) for data in result]
        await SystemRoleMenu.bulk_create(menu_list)

    # 获取角色的菜单
    async def get_menu_by_role_id(self, role_ids: List[int]):
        """根据角色ID获取菜单"""
        menu_ids = await SystemRoleMenu.filter(role_id__in=role_ids).values_list('menu_id', flat=True)
        if len(menu_ids) == 0:
            return []
        lists = await SystemMenu.filter(id__in=menu_ids).order_by("sort").all()
        menus = [await obj.to_dict(m2m=True) for obj in lists]
        return ArrayUtil.list_to_tree(menus, 'id', 'pid', 'children')
